const {
	Controller
} = require("uni-cloud-router");
const {
	success,
	fail,
	verify_token,
	build_token,
	create_uuid,
	encrypt,
	decrypt,
	isFieldExist,
	whereObj,
	isHttpMethod,
	isAdmin,
	isSuperAdmin,
	isAuthorities,
	
} = require('mh-utils');
//静态配置
const createConfig = require('uni-config-center')
const envCfg = createConfig({
	pluginId: 'env'
}).config()

module.exports = class UserController extends Controller {
	// [sys:user:list, sys:user:add, sys:user:update, sys:user:delete]
	
	/**
	 * 检查user表某字段是否已存在
	 * @example ?username=admin
	 * @example ?phone=18988889999
	 */
	async existence() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			var username = ctx.data.username;
			var where = '', filedName, filedValue;
			for(var [key, value] of Object.entries(ctx.query)){
				filedName = key;
				filedValue = value;
			}
			if(typeof filedValue == 'string'){
				where = `${filedName} == '${filedValue}'`
			}else if(typeof filedValue == 'number'){
				where = `${filedName} == ${filedValue}`
			}else{
				where = `${filedName} == '${filedValue}'`
			}
			var userCount = await dbJQL.collection("mh-sys-user")
				.where(where)
				.count();
			if (userCount.total >= 1) {
				return success({
					code: 0,
					message: ""
				})
			} else {
				return fail({
					code: 1,
					message: ""
				})
			}
		}
	}

	/**
	 * 分页查询
	 */
	async page() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:user:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				var where = "";
				
				// 查询条件
				var username = ctx.data.username;
				var nickname = ctx.data.nickname;
				var sex = ctx.data.sex;
				var hasSelf = ctx.data.hasSelf; //是否包含自身
				var organizationId = ctx.data.organizationId;
				var sort = ctx.data.sort || null;
				var order = ctx.data.order || 'asc';
				if (isFieldExist(username)) {
					//模糊查询
					where = whereObj({where,query:`${new RegExp(username,'i')}.test(username)`});
				}
				if (isFieldExist(nickname)) {
					where = whereObj({where,query:`${new RegExp(nickname,'i')}.test(nickname)`});
				}
				if (isFieldExist(sex)) {
					where = whereObj({where,query:`sex==${sex}`});
				};
				if (isFieldExist(organizationId)) {
					where = whereObj({where,query:`organizationId=='${organizationId}'`});
				};
				//super超管能查看所有租户的用户
				if(!isSuperAdmin(ctx)){
					where = whereObj({where,query:`tenantId=='${ctx.auth.tenantId}'`});
				}
				where = whereObj({where,query:`deleted != 1`});
				
				if(hasSelf){
					
				}else{
					//不能看自己的记录，只能上级管理员查看
					where = whereObj({where,query:`_id != '${ctx.auth.loginUserId}'`});
				}
				
				// 分页
				var page = ctx.data.page || 1;
				var limit = ctx.data.limit || 500;
				var result = await dbJQL.collection("mh-sys-user")
					.where(`${where}`)
					.orderBy(`${sort}`, `${order}`)
					.skip((page*1 - 1) * limit)
					.limit(limit*1)
					.get({
						getCount: true
					})
				if(!result.data){
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
				return success({
					code: 0,
					data: {
						list: result.data.map(item=>{
							return {
								...item,
								password: null,
							}
						}),
						count: result.count,
					}
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 查询全部用户（暂时不做）
	 */
	async list() {}
	
	/**
	 * 新增
	 * @example data
	 */
	async add() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'POST')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:user:add')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				var tenantId = '';
				if(isSuperAdmin(ctx)){
					// super超管能为用户选择租户
					tenantId = ctx.data.tenantId || ctx.auth.tenantId;
				}else{
					// 否则默认登录者同一个租户下
					tenantId = ctx.auth.tenantId
				}
				delete ctx.data._id;
				
				//未传入organizationId，默认为根节点公司
				var organizationId = ctx.data.organizationId;
				if(!organizationId) {
					var rootOrg = await dbJQL.collection("mh-sys-organization")
						.where(`isRoot==1 && tenantId=='${tenantId}'`)
						.get({
							getOne: true,
						})
					organizationId = rootOrg.data._id
				}
				
				var result = await dbJQL.collection("mh-sys-user")
					.add({
						...ctx.data,
						"createUserId": ctx.auth.loginUserId,
						"tenantId": tenantId,
						"organizationId": organizationId
					})
				if(result.id) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 导入批量新增
	 */
	async addBatch() {
		
	}

	/**
	 * 修改
	 * @example data
	 */
	async update() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'PUT')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:user:update')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if(ctx.auth.loginUserId != ctx.data.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
			try{
				var userId = ctx.data._id;
				if(!userId) return fail({
					code: 1,
					message: '参数无效'
				})
				delete ctx.data._id; //_id带到查询数据库会报错
				delete ctx.data.tenantId;
				var result = await dbJQL.collection("mh-sys-user")
					.doc(userId)
					.update({
						...ctx.data,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 修改（无权限校验）
	 * @example data
	 */
	async updateNoAuth() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'PUT')){
			try{
				var userId = ctx.data._id;
				if(!userId) return fail({
					code: 1,
					message: '参数无效'
				})
				delete ctx.data._id; //_id带到查询数据库会报错
				delete ctx.data.tenantId;
				var result = await dbJQL.collection("mh-sys-user")
					.doc(userId)
					.update({
						...ctx.data,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 删除
	 * @example ?_id=111111&createUserId=2222222
	 */
	async remove() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'DELETE')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:user:delete')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if(ctx.auth.loginUserId != ctx.query.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
			
			try{
				var userId = ctx.query._id;
				if(!userId) return fail({
					code: 1,
					message: '参数无效'
				})
				var result = await dbJQL.collection("mh-sys-user")
					.doc(userId)
					.update({
						deleted: 1,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 批量删除
	 * @example ?_id=1,2,3&createUserId=8,8,8
	 */
	async removeBatch() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'DELETE')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:user:delete')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				var createUserIdArr = ctx.query.createUserId.split(',')
				for(var i=0; i<createUserIdArr.length; i++){
					if(ctx.auth.loginUserId != createUserIdArr[i]){
						return fail({
							code: 1,
							message: '不可操作非本人的数据'
						})
					}
				}
			}
			try{
				var _ids = ctx.query._id.split(',')
				if(_ids.length == 0) return fail({
					code: 1,
					message: '参数无效'
				})
				var result = await dbJQL.collection("mh-sys-user")
					.where(`in(_id, ${JSON.stringify(_ids)})`)
					.update({
						deleted: 1,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 修改用户状态
	 * @example data={_id, createUserId, status}
	 */
	async status() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'PUT')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:user:update')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if(ctx.auth.loginUserId != ctx.data.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
			
			try{
				var userId = ctx.data._id;
				if(!userId) return fail({
					code: 1,
					message: '参数无效'
				})
				var result = await dbJQL.collection("mh-sys-user")
					.doc(userId)
					.update({
						status: ctx.data.status,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 根据_id查询用户
	 * @example ?_id=111
	 */
	async detail() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:user:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try{
				var result = await dbJQL.collection("mh-sys-user")
					.doc(`${ctx.data._id}`)
					.get({
						getOne: true
					})
				if(result.data){
					return success({
						code: 0,
						data: { ...result.data, password: null}
					})
				}
				return fail({
					code: 1,
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 重置密码
	 * @example data={_id, createUserId}
	 */
	async resetPassword() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'PUT')){
			if(!isAdmin(ctx) && !isSuperAdmin(ctx)){
				if(!isAuthorities(ctx, 'sys:user:update')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if(ctx.auth.loginUserId != ctx.data.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
			
			try{
				var userId = ctx.data._id;
				var password = ctx.data.password;
				if(!userId || !password) return fail({
					code: 1,
					message: '参数无效'
				})
				var result = await dbJQL.collection("mh-sys-user")
					.doc(userId)
					.update({
						password,
						updateTime: new Date().getTime()
					})
				if(result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				}else{
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 修改密码
	 * @example 
	 */
	async updateOldPassword(){
		
	}
	
	/**
	 * 获取租户
	 */
	async tenantData(){
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if(isHttpMethod(ctx, 'GET')){
			try{
				var result = await dbJQL.collection("mh-sys-tenant")
					.where("_id != '0'")
					.get()
				var d = result.data
				if(d){
					return success({
						code: 0,
						data: d
					})
				}
				return fail({
					code: 1,
				})
			}catch(e){
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	
	
	
	
	
	
	
};
